package com.yupi.yuoj.common;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import io.lettuce.core.protocol.ConnectionFacade;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

@Component
public class MQInit {
    public static String EXCHANG_NAME="exchange_01";
    public static  String DEAD_EXCHANG_NAME="dead_exchange_01";
    public static  String QUEUE_NAME="queue_01";
    public static String DEAD_QUEUE_NAME="dead_queue_01";
    public static String SCRECT_NAME="queue_key";
    public static String DEAD_SCRECT_NAME="dead_key";
    public static void mqinit(){
        ConnectionFactory factory = new ConnectionFactory();

        factory.setHost("localhost");
        factory.setPort(5672);
        Connection connection = null;
        try {
            connection = factory.newConnection();
            Channel channel=connection.createChannel();

            //创建正常和死信交换机
            channel.exchangeDeclare(EXCHANG_NAME,"direct");
            channel.exchangeDeclare(DEAD_EXCHANG_NAME,"direct");
            //正常队列绑定死信队列信息
            Map<String, Object> params = new HashMap<>();
            //正常队列设置死信交换机 参数 key 是固定值
            params.put("x-dead-letter-exchange", DEAD_EXCHANG_NAME);
            params.put("x-dead-letter-routing-key", DEAD_SCRECT_NAME);
            params.put("x-message-ttl",60000);

            //创建死信队列
            channel.queueDeclare(DEAD_QUEUE_NAME,true,false,false,null);
            channel.queueBind(DEAD_QUEUE_NAME,DEAD_EXCHANG_NAME,DEAD_SCRECT_NAME);

            //创建正常队列
            channel.queueDeclare(QUEUE_NAME,true,false,false,params);
            channel.queueBind(QUEUE_NAME,EXCHANG_NAME,SCRECT_NAME);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (TimeoutException e) {
            throw new RuntimeException(e);
        }
    }
}
